import { Server } from "socket.io";
import WeChaty from "../utils/WeChaty";

let alreadyPay: string[] = [];
let currentOrderId = "";

// 每半小时看一下是否是23点，如果是就清空已支付列表
setInterval(() => {
  if (new Date().getHours() === 23) {
    alreadyPay = [];
  }
}, 1000 * 60 * 30);

const TARGETMONEY = 9;

export function createSocket(server: any) {
  const io = new Server(server);
  let wc = WeChaty.create();

  io.on("connection", (socket) => {
    wc = WeChaty.create();
    // 登录
    socket.on("login", async () => {
      // 删除实例
      WeChaty.removeIns();

      // 重新获取登录地址
      wc = WeChaty.create();
      const codeUrl = await wc.run();
      socket.emit("login", codeUrl);

      wc.onloginCallback = () => {
        socket.emit("loginSuccess");
      };
    });

    socket.on("checkPay", (id: string) => {
      currentOrderId = id;
      let res = alreadyPay.includes(id);

      socket.emit("payed", res);
    });

    // 支付成功发送消息
    wc.onMessageCallback = (money: string) => {
      // 大于9元则支付成功
      if (+money > TARGETMONEY) {
        alreadyPay.push(currentOrderId);
        currentOrderId = "";
        socket.emit("paySuccess", money);
      }
    };

    // 用户离开
    socket.on("disconnecting", () => {
      io.emit("userout");
    });
  });
}
